class ThreadDemo3 {
	static Object msg = new Object();

	static class ThreadA extends Thread {

		public void run() {
			for (int i = 0; i < 100 ; i++ ) {
				synchronized (msg) {
					try {
						msg.notify();
						System.out.println("水装满了");
						msg.wait(); // 进入等待并释放A线程的锁
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	static class ThreadB extends Thread {

		public void run() {
			for (int i = 0; i < 100 ; i++ ) {
				synchronized (msg) {
					try {
						msg.notify();
						System.out.println("拧好瓶盖");
						msg.wait(); // 进入等待并释放B线程的锁
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	// 演示线程通信
	public static void test2() {
		Thread t1 = new ThreadA();
		Thread t2 = new ThreadB();
		t1.start();
		t2.start();
	}

	// 演示线程同步
	public static void test1() {
		// 一个窗口卖票
		/*Thread t1 = new Thread(new SaleTask());
		t1.setName("1号窗口");
		t1.start();*/
		// 3个窗口卖票
		Runnable task = new SaleTask();
		Thread t1 = new Thread(task);
		t1.setName("1号窗口");
		t1.start();
		Thread t2 = new Thread(task);
		t2.setName("2号窗口");
		t2.start();
		Thread t3 = new Thread(task);
		t3.setName("3号窗口");
		t3.start();
	}

	public static void main(String[] args) throws Exception {
		test2();
	}
}

class SaleTask implements Runnable {
	int tickects = 1000;
	Object lock = new Object();

	public synchronized void run() {
		String name = Thread.currentThread().getName();
		/*for (int i = tickects; i > 0; ) {
			i--;
			System.out.println(name + "卖出一张票，余票：" + i);
		}*/
		/*while(--tickects >= 0)  {
			System.out.println(name + "卖出一张票，余票：" + tickects);
		}*/
		// 非原子性操作，会存在卖超的情况
		/*while (tickects > 0) {

			synchronized (this) {
				tickects--;
				System.out.println(name + "卖出一张票，余票：" + tickects);
			}
		}*/

		/*while (true) {
			// 将3个步骤都锁起来，形成原子操作，可以规避这个问题
			synchronized (this) {
				if (tickects > 0) {
					tickects--;
					System.out.println(name + "卖出一张票，余票：" + tickects);
				} else {
					break;
				}
			}
		}*/
		/*while (true) {
			if (tickects > 0) {
				tickects--;
				System.out.println(name + "卖出一张票，余票：" + tickects);
			} else {
				break;
			}
		}*/
	}
}